import sys
from pathlib import Path

file = Path(__file__).resolve()
parent, top = file.parent, file.parents[3]

sys.path.append(str(top))
try:
    sys.path.remove(str(parent))
except ValueError: # Already removed
    pass

__package__ = 'server.report.models'


from sqlalchemy import JSON, Column, Float, Integer, String, Text, Enum, DateTime, event
from server.report.utils.mysql_utils import Base, mysql_util
from passlib.hash import bcrypt
from datetime import datetime, timedelta


def datetime_8():
    # 将 UTC 时间转换为北京时间存储到数据库
    datetime_add_8 = datetime.utcnow() + timedelta(hours=8)
    return datetime_add_8


class User(Base):
    __tablename__ = "user"
    __table_args__ = {'comment': '用户表', 'mysql_charset': 'utf8mb4', 'extend_existing': True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_name = Column(String(10), nullable=False)
    passwd_hash = Column(String(60), nullable=False)
    email = Column(String(100), nullable=False)
    department = Column(String(50), nullable=False)
    # 用户角色：只能是 "USER" 或 "ADMIN"
    role = Column(Enum("USER", "ADMIN", name="user_roles"), nullable=False)
    # 创建时间：插入时自动生成
    created_at = Column(DateTime, default=datetime_8)
    # 更新时间：每次更新时自动更新
    updated_at = Column(DateTime, default=datetime_8, onupdate=datetime_8)
    # 状态：只能是 "Y"（有效）或 "N"（无效）
    status = Column(Enum("Y", "N", name="user_status"), nullable=False, default="Y")

    @property
    def password(self):
        raise AttributeError("密码不可读取")

    @password.setter
    def password(self, password):
        self.passwd_hash = bcrypt.hash(password)

    def check_password(self, password):
        return bcrypt.verify(password, self.passwd_hash)


class Report(Base):
    __tablename__ = 'report'
    __table_args__ = {'comment': '报告表', 'mysql_charset': 'utf8mb4', 'extend_existing': True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    report_name = Column(String(50), nullable=False)  # 报告名称
    input_file_path = Column(String(100), nullable=False)  # 上传报告路径
    output_file_path = Column(String(100)) # 生成报告路径
    scene = Column(String(8), nullable=False)  # 报告场景
    user_id = Column(Integer, nullable=False, comment='User id 做关联')  # 经办人
    start_date = Column(DateTime, default=datetime_8)  # 经办发起日期
    generate_date = Column(DateTime)  # 报告生成日期
    status = Column(
        Enum("NOT_START", "DOING", "FAILED", "DONE", "CANCELLED"),
        default="NOT_START"
    )  # 报告状态


# 报告场景
class Scene(Base):
    __tablename__ = 'scene'
    __table_args__ = {'comment': '场景表', 'mysql_charset': 'utf8mb4', 'extend_existing': True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    scene = Column(String(50), nullable=False)


if __name__ == "__main__":
    
    Base.metadata.create_all(bind=mysql_util.sqlalchemy_engine)

    admin = User(user_name="ADMIN", email="ADMIN@storagex.ai", department="Software", role="ADMIN") 
    admin.password="admin123"

    user = User(user_name="USER", email="USER@storagex.ai", department="Software", role="USER")
    user.password = "user123"

    scene1 = Scene(scene="单一客户")
    scene2 = Scene(scene="科技金融")
    scene3 = Scene(scene="集团客户")

    # with mysql_util.get_db() as db:
    #     mysql_util.db_add_commit_refresh(db, admin)
    #     mysql_util.db_add_commit_refresh(db, user)
    #     mysql_util.db_add_commit_refresh(db, scene1)
    #     mysql_util.db_add_commit_refresh(db, scene2)
    #     mysql_util.db_add_commit_refresh(db, scene3)

